# 自己写一个自定义的验证类
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import User,UserToken  # 导入你自己写的 User 表
import base64
from django.utils import timezone
from datetime import timedelta

class MyUserBasicAuth(BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.lower().startswith('basic '):
            return None
        try:
            encoded = auth_header.split(' ')[1]
            decoded = base64.b64decode(encoded).decode('utf-8')
            username, password = decoded.split(':', 1)
        except Exception:
            raise AuthenticationFailed('无法解析认证信息')
        try:
            user = User.objects.get(username=username)
            if user.password != password:
                raise AuthenticationFailed('密码错误')
        except User.DoesNotExist:
            raise AuthenticationFailed('用户不存在')
        # 返回的是你自定义的 User，不是 auth.User
        return (user, None)
    

class MyTokenAuth(BaseAuthentication):
    def authenticate(self, request):
        token = request.headers.get('Authorization')
        if not token or not token.startswith('Token '):
            return None
        token_value = token.split()[1]
        print(token_value)
        try:
            user_token = UserToken.objects.get(token=token_value)
        except UserToken.DoesNotExist:
            raise AuthenticationFailed('无效的Token')
        # 校验 token 是否过期（5分钟）
        if timezone.now() - user_token.create_time > timedelta(minutes=5):
            raise AuthenticationFailed('Token已过期')
        return (user_token.user, None)
        
        
class MySessionAuth(BaseAuthentication):
    def authenticate(self, request):
        user_id = request.session.get('user_id')
        if not user_id:
            return None
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            raise AuthenticationFailed('用户不存在')
        return (user, None)
    
import redis
class MyRedisAuth(BaseAuthentication):
    # 我的设想是利用redis实现自我的验证操作，这里省略了具体实现
    def __init__(self):
        # 连接 Redis（这里假设你使用默认设置）
        self.redis_conn = redis.StrictRedis(host='localhost', port=6379, db=1, decode_responses=True)
    def authenticate(self, request):
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('token'):
            return None
        token = auth_header.split()[1]
        print(f"接收到的 token: {token}")
        # 从 Redis 获取 user_id 和创建时间
        user_id = self.redis_conn.get(f"token:{token}")
        if not user_id:
            raise AuthenticationFailed('无效的 token 或已过期')
        # 可选：校验 token 是否快过期（只要 Redis 设置了过期时间其实就够了）
        ttl = self.redis_conn.ttl(f"token:{token}")
        if ttl < 0:
            raise AuthenticationFailed('token 已过期')
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            raise AuthenticationFailed('用户不存在')
        return (user, None)
        